
function isFn(value) {
  const type = Object.prototype.toString.call(value);
  return type === '[object Function]';
}

function isNode(value) {
  return value !== undefined && value instanceof HTMLElement && value.nodeType === 1;
}

function listenNode(node, type, callback) {
  node.addEventListener(type, callback);
  return {
    destroy(cb) {
      node.removeEventListener(type, callback);
      if(typeof cb === 'function') cb();
    },
  };
}

function addListener(target, type, callback) {
  if (!target && !type && !callback) {
    throw new Error('缺少参数');
  }
  if (!isFn(callback)) {
    throw new TypeError('Third argument must be a Function');
  }
  if (isNode(target)) {
    return listenNode(target, type, callback);
  }
  throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');
}

function listenNodeList(nodeList, type, callback) {
  Array.prototype.forEach.call(nodeList, node => {
    node.addEventListener(type, callback);
  });
  return {
    destroy() {
      Array.prototype.forEach.call(nodeList, node => {
        node.removeEventListener(type, callback);
      });
    },
  };
}

export {
  listenNodeList,
  addListener
};
